package com.jzt.gateway.utils;

import org.apache.commons.lang3.StringUtils;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Objects;

/**
 * 作者：lizw <br/>
 * 创建时间：2020/06/19 15:32 <br/>
 */
public class UrlPathUtils {
    private static final char SEPARATE = '/';

    /***
     * 连接多个url路径,保证不会出现多余的"/",最后一个字符也不是"/"<br />
     * <pre>
     * connectPath("http://domain.com", "a/b")  -> "http://domain.com/a/b"
     * connectPath("pre", "/a/b")               -> "pre/a/b"
     * connectPath("pre ", " a/b ")             -> "pre/a/b"
     * connectPath("pre", null, " a/b ")        -> "pre/a/b"
     * connectPath("pre", "", "/", " a/b ")     -> "pre/a/b"
     * connectPath("/a/b/c", "/d/", "/e/")      -> "/a/b/c/d/e/f/"
     * connectPath("", "/", "/", "/")           -> ""
     * connectPath()                            -> ""
     * </pre>
     */
    public static String connectPath(String... paths) {
        StringBuilder sb = new StringBuilder(64);
        if (paths != null) {
            for (String s : paths) {
                String path = StringUtils.trim(s);
                if (StringUtils.isBlank(path)) {
                    continue;
                }
                // 第一个
                if (sb.length() <= 0) {
                    sb.append(path);
                    continue;
                }
                boolean before = Objects.equals(sb.charAt(sb.length() - 1), SEPARATE);
                boolean after = Objects.equals(path.charAt(0), SEPARATE);
                if (!Objects.equals(before, after)) {
                    sb.append(path);
                } else if (before && after) {
                    sb.append(path.substring(1));
                } else {
                    sb.append(SEPARATE).append(path);
                }
            }
        }
        if (sb.length() > 0 && Objects.equals(sb.charAt(sb.length() - 1), SEPARATE)) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    public static URL parseUrl(String urlStr) {
        URL url = null;
        try {
            url = new URL(urlStr);
        } catch (MalformedURLException ignored) {
        }
        return url;
    }

    public static URI parseUri(String uriStr) {
        URI uri = null;
        try {
            uri = new URI(uriStr);
        } catch (URISyntaxException ignored) {
        }
        return uri;
    }
}
